﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HTTT.Utilities;
using System.Web.Security;

namespace HTTT.admin.htuser
{
    public partial class AssignRole : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
                CheckPermission();
            }
        }

        private void LoadData()
        {
            string username = Request.QueryString["ID"];
            LoadDetail(username);
        }

        private void LoadDetail(string username)
        {
            txtUsername.Text = username;
            //Load role list
            // Get all of the roles 
            string[] roles = Roles.GetAllRoles();
            chkRoleList.DataSource = roles;
            chkRoleList.DataBind(); 

            // Select role of current user
            string[] selectedUsersRoles = Roles.GetRolesForUser(username);

            // Loop through the Repeater's Items and check or uncheck the checkbox as needed 

            foreach (string role in selectedUsersRoles)
            {
                foreach (ListItem item in chkRoleList.Items)
                {
                    if (role == item.Value) item.Selected = true;
                }
            } 
        }

        
        private void CheckPermission()
        {
            if (Page.User.IsInRole(Constants.ROLE_SUPER_ADMINISTRATOR))
            {
                //
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatMsgThenRedirect("Bạn không có quyền", "/admin/AminIndex.aspx"), true);
            }
        }


        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;
            String[] userlist = {username};
            // Role of current user
            string[] selectedUsersRoles = Roles.GetRolesForUser(username);
            foreach(ListItem item in chkRoleList.Items)
            {
                if (item.Selected)
                {
                    if (!selectedUsersRoles.Contains(item.Value))
                    {
                        Roles.AddUsersToRole(userlist, item.Value);
                    }
                }
                else
                {
                    if (selectedUsersRoles.Contains(item.Value))
                    {
                        Roles.RemoveUserFromRole(txtUsername.Text, item.Value);
                    }
                }
            }
            Response.Redirect("UserList.aspx");
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx");
        }
    }
}